/**
 * Copyright (C), 2021, 中电福富信息科技有限公司
 * FileName: TenantServiceImpl
 * Author:   xujiajun
 * Date:     2021/3/1 16:37
 */
package com.example.demo.service.impl;

import com.example.demo.client.SmQryClient;
import com.example.demo.mapper.TenancyMapper;
import com.ffcs.oss.param.vm.QueryPageVm;
import com.example.demo.security.SecurityUtils;
import com.example.demo.service.TenancyService;
import com.example.demo.web.rest.constant.DatabaseConstant;
import com.example.demo.web.rest.evt.TableIdSizeEvt;
import com.example.demo.web.rest.evt.TenancyEvt;
import com.example.demo.web.rest.evt.UserTenancyInfoEvt;
import com.example.demo.web.rest.vm.TenancyVm;
import com.example.demo.web.rest.vm.UserTenancyVm;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Description:
 * @Author xujiajun
 * @Date 2021/3/1  16:37
 */
@Service
public class TenancyServiceImpl implements TenancyService {

    protected Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private TenancyMapper tenancyMapper;

    @Autowired
    private SmQryClient smQryClient;

    @Override
    public QueryPageVm<TenancyVm> listTenancyInfo(TenancyEvt evt) {

        if (evt.getPageNo() != null && evt.getPageSize() != null && evt.isCountTotal()) {
            Page page = PageHelper.startPage(evt.getPageNo(), evt.getPageSize(), evt.isCountTotal());
            List<TenancyVm> list = tenancyMapper.listTenancyInfo(evt);
            return QueryPageVm.getInstance(evt, list, page.getTotal());
        } else {
            List<TenancyVm> list = tenancyMapper.listTenancyInfo(evt);
            return QueryPageVm.getInstance(evt, list, 0l);
        }
    }

    @Override
    public QueryPageVm<UserTenancyVm> listUserTenancyInfo(UserTenancyInfoEvt evt) {
        Page page = PageHelper.startPage(evt.getPageNo(), evt.getPageSize(), evt.isCountTotal());
        if (evt.getPageNo() != null && evt.getPageSize() != null && evt.isCountTotal()) {
            QueryPageVm<UserTenancyVm> instance = QueryPageVm.getInstance(evt, tenancyMapper.listUserTenancyInfo(evt.getAlias()), page.getTotal());
            return instance;
        } else {
            QueryPageVm<UserTenancyVm> instance = QueryPageVm.getInstance(evt, tenancyMapper.listUserTenancyInfo(evt.getAlias()), 0l);
            return instance;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertTenancyInfo(TenancyEvt evt) {
        if (isTenancyNameExists(evt)) {
            throw new RuntimeException("租户名称重复");
        }
        try {

            TenancyVm vm = new TenancyVm();
            Long id = smQryClient.getTableId(new TableIdSizeEvt(DatabaseConstant.TABLE_NAME_TENANCY));
            BeanUtils.copyProperties(evt, vm);
            String loginName = SecurityUtils.getCurrentUserLogin().get();
            Date now = new Date();
            vm.setId(id);
            vm.setCreateTime(now);
            vm.setLastUpdateTime(now);
            vm.setCreateUserName(loginName);
            vm.setLastUpdateUserName(loginName);
            tenancyMapper.insert(vm);

            evt.setId(id);
            updUserRelatedTenancy(evt);
            return true;
        }catch (Exception e) {
            logger.error("新增租户异常", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delTenancyInfo(TenancyEvt evt) {
        if (evt == null || evt.getId() <= 0) {
            logger.error("删除租户失败，参数异常{}", evt);
            return false;
        }
        try {
            TenancyVm vm = new TenancyVm();
            BeanUtils.copyProperties(evt, vm);
            tenancyMapper.delete(vm);
            return true;
        }catch (Exception e) {
            logger.error("删除租户异常", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updTenancyInfo(TenancyEvt evt) {
        if (evt == null || evt.getId() <= 0 || StringUtils.isBlank(evt.getTenancyName())) {
            logger.error("修改租户失败，参数异常{}", evt);
            return false;
        }
        if (isTenancyNameExists(evt)) {
            throw new RuntimeException("租户名称重复");
        }
        try {
            TenancyVm vm = new TenancyVm();
            BeanUtils.copyProperties(evt, vm);
            String loginName = SecurityUtils.getCurrentUserLogin().get();
            Date now = new Date();
            vm.setLastUpdateTime(now);
            vm.setLastUpdateUserName(loginName);
            tenancyMapper.updateByPrimaryKey(vm);
            updUserRelatedTenancy(evt);
            return true;
        }catch (Exception e) {
            logger.error("修改租户异常", e);
            return false;
        }
    }

    @Override
    public Boolean isTenancyNameExists(TenancyEvt evt) {
        if (StringUtils.isBlank(evt.getTenancyName())) {
            throw new RuntimeException("租户名称不能为空");
        }
        return tenancyMapper.isTenancyNameExists(evt) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updUserRelatedTenancy(TenancyEvt evt) {
        if (evt.getId() == null || evt.getId() <= 0) {
            throw new RuntimeException("租户id为空");
        }
        try {
            if (evt.getAddUserIdList() != null && evt.getAddUserIdList().size() > 0) {
                tenancyMapper.updUserRelateTenancy(evt);
            }
            if (evt.getDelUserIdList() != null && evt.getDelUserIdList().size() > 0) {
                tenancyMapper.updUserUnRelateTenancy(evt);
            }
        }catch (Exception e) {
            logger.error("修改用户租户关系表异常", e);
            return false;
        }
        return true;
    }

    @Override
    public Boolean updTenancyStatusAndRemark(TenancyEvt evt) {
        logger.info("修改租户状态及备注，入参:{}", evt.toString());
        evt.setLastUpdateTime(new Date());
        evt.setLastUpdateUserName(SecurityUtils.getCurrentUserLogin().get());
        return tenancyMapper.updTenancyStatusAndRemark(evt);
    }
}